package com.blog.Bard.common.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
@ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
public class DruidConfiguration {
	
	@Value("${spring.datasource.logUserName:''}")
	private String logUserName;
	
	@Value("${spring.datasource.logPassword:''}")
	private String logPassword;
	
	@Primary
	@Bean(name = "bardDataSource")
	@Qualifier("bardDataSource")
	@ConfigurationProperties("spring.datasource.bard")
	public DataSource dataSourceOne() {
		return DruidDataSourceBuilder.create().build();
	}
	
	
	//配置一个servlet，用于管理druid数据源信息
	@Bean
	public ServletRegistrationBean<StatViewServlet> statViewServlet() {
		ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");
		//设置控制台管理用户
		servletRegistrationBean.addInitParameter("loginUsername", logUserName);
		servletRegistrationBean.addInitParameter("loginPassword", logPassword);
		//是否可以重置数据
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		return servletRegistrationBean;
	}
	
	//配置一个filter，用于管理过滤策略
//	@Bean
//	public FilterRegistrationBean<WebStatFilter> statFilter() {
//		//创建过滤器
//		FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(new WebStatFilter());
//		//设置过滤器过滤路径
//		filterRegistrationBean.addUrlPatterns("/*");
//		//忽略过滤的形式
//		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
//		return filterRegistrationBean;
//	}
	
}